package com.ruoyi.web.service.impl;

import com.ruoyi.web.service.ApiService;
import com.ruoyi.xhs.entity.XhsSearchResult;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ApiServiceImpl
 *
 * @author Wayne Wei
 * @version 1.0
 * @date 2025/6/19
 * @description 小红书接口实现类
 */
@Service
public class ApiServiceImpl implements ApiService {

    private String baseUrl = "https://edith.xiaohongshu.com";

    @Override
    public XhsSearchResult searchSomeNote(String query, int require_num, String cookies_str, int sort_type_choice, int note_type, int note_time, int note_range, int pos_distance, String geo, Map<String, Object> proxies) {
        int page = 1;
        List<Map<String, Object>> noteList = new ArrayList<>();
        boolean success = false;
        String msg = "";

        try {
            while (true) {
                XhsSearchResult result = search_note(query, cookies_str, page, sort_type_choice, note_type, note_time, note_range, pos_distance, geo, proxies);

                success = result.success;
                msg = result.msg;

                if (!success) {
                    throw new Exception(msg);
                }

                Map<String, Object> resJson = result.resJson;
                if (!resJson.containsKey("data") || !((Map<String, Object>) resJson.get("data")).containsKey("items")) {
                    break;
                }

                List<Map<String, Object>> notes = (List<Map<String, Object>>) ((Map<String, Object>) resJson.get("data")).get("items");
                noteList.addAll(notes);
                page++;

                if (noteList.size() >= require_num || !(boolean) ((Map<String, Object>) resJson.get("data")).get("has_more")) {
                    break;
                }
            }
        } catch (Exception e) {
            success = false;
            msg = e.getMessage();
        }

        if (noteList.size() > require_num) {
            noteList = noteList.subList(0, require_num);
        }

        Map<String, Object> resJson = new HashMap<>();
        resJson.put("items", noteList);
        return new XhsSearchResult(success, msg, resJson);
    }

    // 模拟 search_note 方法，实际需实现
    public XhsSearchResult search_note(String query, String cookies_str, int page, int sort_type_choice, int note_type, int note_time, int note_range, int pos_distance, String geo, Map<String, Object> proxies) {
        JSONObject resJson = null;
        String sortType = "general";
        switch (sort_type_choice) {
            case 1:
                sortType = "time_descending";
                break;
            case 2:
                sortType = "popularity_descending";
                break;
            case 3:
                sortType = "comment_descending";
                break;
            case 4:
                sortType = "collect_descending";
                break;
        }

        String filterNoteType = "不限";
        switch (note_type) {
            case 1:
                filterNoteType = "视频笔记";
                break;
            case 2:
                filterNoteType = "普通笔记";
                break;
        }

        String filterNoteTime = "不限";
        switch (note_time) {
            case 1:
                filterNoteTime = "一天内";
                break;
            case 2:
                filterNoteTime = "一周内";
                break;
            case 3:
                filterNoteTime = "半年内";
                break;
        }

        String filterNoteRange = "不限";
        switch (note_range) {
            case 1:
                filterNoteRange = "已看过";
                break;
            case 2:
                filterNoteRange = "未看过";
                break;
            case 3:
                filterNoteRange = "已关注";
                break;
        }

        String filterPosDistance = "不限";
        switch (pos_distance) {
            case 1:
                filterPosDistance = "同城";
                break;
            case 2:
                filterPosDistance = "附近";
                break;
        }

        if (geo != null && !geo.isEmpty()) {
            // 假设 geo 是 JSON 字符串，这里简单处理
            geo = geo.replaceAll("\\s+", "");
        }

        boolean success = false;
        String msg = "";

        try {
            String api = "/api/sns/web/v1/search/notes";
            JSONObject data = new JSONObject();
            data.put("keyword", query);
            data.put("page", page);
            data.put("page_size", 20);
            data.put("search_id", generate_x_b3_traceid(21));
            data.put("sort", "general");
            data.put("note_type", 0);
            data.put("ext_flags", new JSONArray());

            JSONArray filters = new JSONArray();
            JSONObject sortFilter = new JSONObject();
            sortFilter.put("type", "sort_type");
            JSONArray sortTags = new JSONArray();
            sortTags.put(sortType);
            sortFilter.put("tags", sortTags);
            filters.put(sortFilter);

            JSONObject noteTypeFilter = new JSONObject();
            noteTypeFilter.put("type", "filter_note_type");
            JSONArray noteTypeTags = new JSONArray();
            noteTypeTags.put(filterNoteType);
            noteTypeFilter.put("tags", noteTypeTags);
            filters.put(noteTypeFilter);

            JSONObject noteTimeFilter = new JSONObject();
            noteTimeFilter.put("type", "filter_note_time");
            JSONArray noteTimeTags = new JSONArray();
            noteTimeTags.put(filterNoteTime);
            noteTimeFilter.put("tags", noteTimeTags);
            filters.put(noteTimeFilter);

            JSONObject noteRangeFilter = new JSONObject();
            noteRangeFilter.put("type", "filter_note_range");
            JSONArray noteRangeTags = new JSONArray();
            noteRangeTags.put(filterNoteRange);
            noteRangeFilter.put("tags", noteRangeTags);
            filters.put(noteRangeFilter);

            JSONObject posDistanceFilter = new JSONObject();
            posDistanceFilter.put("type", "filter_pos_distance");
            JSONArray posDistanceTags = new JSONArray();
            posDistanceTags.put(filterPosDistance);
            posDistanceFilter.put("tags", posDistanceTags);
            filters.put(posDistanceFilter);

            data.put("filters", filters);
            data.put("geo", geo);

            JSONArray imageFormats = new JSONArray();
            imageFormats.put("jpg");
            imageFormats.put("webp");
            imageFormats.put("avif");
            data.put("image_formats", imageFormats);

            Map<String, Object> requestParams = generate_request_params(cookies_str, api, data);
            @SuppressWarnings("unchecked")
            Map<String, String> headers = (Map<String, String>) requestParams.get("headers");
            @SuppressWarnings("unchecked")
            Map<String, String> cookies = (Map<String, String>) requestParams.get("cookies");
            String postData = (String) requestParams.get("data");

            URL url = new URL(baseUrl + api);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            // 设置 headers
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // 设置 cookies
            StringBuilder cookieString = new StringBuilder();
            for (Map.Entry<String, String> entry : cookies.entrySet()) {
                if (cookieString.length() > 0) {
                    cookieString.append("; ");
                }
                cookieString.append(entry.getKey()).append("=").append(entry.getValue());
            }
            if (cookieString.length() > 0) {
                conn.setRequestProperty("Cookie", cookieString.toString());
            }

            // 发送请求体
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.writeBytes(postData);
                wr.flush();
            }

            int responseCode = conn.getResponseCode();
            StringBuilder response = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }

            resJson = new JSONObject(response.toString());
            success = resJson.getBoolean("success");
            msg = resJson.getString("msg");
        } catch (Exception e) {
            success = false;
            msg = e.getMessage();
        }

//        return new XhsSearchResult(success, msg, resJson);
        return null;
    }

    // 模拟 generate_x_b3_traceid 方法
    private String generate_x_b3_traceid(int length) {
        // 实际实现需要根据具体逻辑编写
        return "mock_trace_id";
    }

    // 模拟 generate_request_params 方法
    private Map<String, Object> generate_request_params(String cookies_str, String api, JSONObject data) {
        // 实际实现需要根据具体逻辑编写
        Map<String, Object> result = new HashMap<>();
        result.put("headers", generate_headers(cookies_str, api));
        result.put("cookies", new HashMap<String, String>());
        result.put("data", data.toString());
        return result;
    }

    // 对应 Python 的 generate_xs_xs_common 方法，需根据实际 JS 逻辑实现
    private Map<String, Object> generate_xs_xs_common(String a1, String api, String data) {
        // 实际实现需要调用 JS 逻辑，这里模拟返回
        Map<String, Object> ret = new HashMap<>();
        ret.put("xs", "mock_xs");
        ret.put("xt", 12345);
        ret.put("xs_common", "mock_xs_common");
        return ret;
    }

    // 对应 Python 的 generate_headers 方法
    private Map<String, Object> generate_headers(String a1, String api) {
        Map<String, Object> result = new HashMap<>();
        Map<String, String> headers = get_request_headers_template();

        Map<String, Object> xsResult = generate_xs_xs_common(a1, api, null);
        String xs = (String) xsResult.get("xs");
        Object xt = xsResult.get("xt");
        String xsCommon = (String) xsResult.get("xs_common");
        String xB3TraceId = generate_x_b3_traceid(16);

        headers.put("x-s", xs);
        headers.put("x-t", String.valueOf(xt));
        headers.put("x-s-common", xsCommon);
        headers.put("x-b3-traceid", xB3TraceId);

//        if (data != null && !data.isEmpty()) {
//            try {
//                JSONObject jsonData = new JSONObject(data);
//                data = jsonData.toString();
//            } catch (Exception e) {
//                // 处理异常
//            }
//        }

        result.put("headers", headers);
//        result.put("data", data);
        return result;
    }

    // 对应 Python 的 get_request_headers_template 方法
    private Map<String, String> get_request_headers_template() {
        Map<String, String> headers = new HashMap<>();
        headers.put("authority", "edith.xiaohongshu.com");
        headers.put("accept", "application/json, text/plain, */*");
        headers.put("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers.put("cache-control", "no-cache");
        headers.put("content-type", "application/json;charset=UTF-8");
        headers.put("origin", "https://www.xiaohongshu.com");
        headers.put("pragma", "no-cache");
        headers.put("referer", "https://www.xiaohongshu.com/");
        headers.put("sec-ch-ua", "\"Not A(Brand\";v=\"99\", \"Microsoft Edge\";v=\"121\", \"Chromium\";v=\"121\"");
        headers.put("sec-ch-ua-mobile", "?0");
        headers.put("sec-ch-ua-platform", "\"Windows\"");
        headers.put("sec-fetch-dest", "empty");
        headers.put("sec-fetch-mode", "cors");
        headers.put("sec-fetch-site", "same-site");
        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0");
        headers.put("x-b3-traceid", "");
        headers.put("x-mns", "unload");
        headers.put("x-s", "");
        headers.put("x-s-common", "");
        headers.put("x-t", "");
//        headers.put("x-xray-traceid", generate_xray_traceid());
        return headers;
    }

    // 对应 Python 的 generate_request_params 方法
//    private Map<String, Object> generate_request_params(String cookies_str, String api, String data) {
//        Map<String, String> cookies = trans_cookies(cookies_str);
//        String a1 = cookies.get("a1");
//        return generate_headers(a1, api, data);
//    }

    // 模拟 trans_cookies 方法，需根据实际实现
    private Map<String, String> trans_cookies(String cookies_str) {
        Map<String, String> cookies = new HashMap<>();
        cookies.put("a1", "mock_a1");
        return cookies;
    }

}